package fr.lille.inria.adam.lifl.EcoGardeInventory.Tasks;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.message.BasicNameValuePair;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;

import android.util.Log;
import fr.lille.inria.adam.lifl.EcoGardeInventory.Utils.Constantes;

public class RetrieveComportementsTask extends
		HttpAsyncTask<String, Map<String, String>> {

	private static final String TAG = "RetrieveComportementsTask";

	@Override
	protected Map<String, String> doInBackground(String... params) {
		Log.d(TAG, "start refresh cats");
		Map<String, String> result = new HashMap<String, String>();
		Log.d(TAG, "deb retrieve");
		HttpPost allRequest = new HttpPost(Constantes.HTTP_SECOND_GROUP); //je récupère la page de recherche
		List<NameValuePair> pairs = new ArrayList<NameValuePair>();
		pairs.add(new BasicNameValuePair("groupe", params[0]));
		try {
			allRequest.setEntity(new UrlEncodedFormEntity(pairs));
			// Et j'extrais les catgories et leurs identifiants depuis la liste
			// droulante
			HttpResponse catResult = browser.execute(allRequest);
			Document doc = Jsoup.parse(super.getStringContent(catResult));
			Elements options = doc.select("select#listeComportement>option");
			for (Element option : options) {
				if (option.attr("value").equals(""))
					continue;
				result.put(option.text(), option.attr("value"));
			}
			Log.d(TAG,
					String.format("done refresh cats (%d results)",
							result.size()));
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
}
